﻿using System;
using System.Linq;
using Eric.SerialPorts;
using SerialPortWrappers.Test.Services;

namespace SerialPortWrappers.Test.Server
{
    internal class ServerEnd
    {
        private readonly SerialPortWrapper _serialPort;

        public ServerEnd()
        {
            _serialPort = new SerialPortWrapper(new SerialPortParameter("COM2"), new TestDataVerifier());
            _serialPort.BizCommandReceivedEvent += SerialPortBizCommandReceivedEvent;
            _serialPort.ErrorReceived += _serialPort_ErrorReceived;
        }

        void _serialPort_ErrorReceived(object sender, System.IO.Ports.SerialErrorReceivedEventArgs e)
        {
            Console.WriteLine("Error occured, type is: " + e.EventType + ".");
        }

        void SerialPortBizCommandReceivedEvent(object sender, SerialPortWrapperDataEventArgs e)
        {
            if (e.Bytes == null || e.Bytes.Count() != 3)
                return;
            if (e.Bytes[0] == (byte)CommandType.Add)
            {
                var sum = (ushort)(e.Bytes[1] + e.Bytes[2]);
                var sumBytes = BitConverter.GetBytes(sum);
                Console.WriteLine("The sum of 2 and 1 is:" + sum + ". Start send result.");

                _serialPort.Send(new byte[] { (byte)CommandType.Add, sumBytes[0], sumBytes[1] });
                Console.WriteLine("Finish send result of sum.");
            }
            else if (e.Bytes[0] == (byte)CommandType.Reduce)
            {
                var diff = (ushort)(e.Bytes[1] - e.Bytes[2]);
                var dffBytes = BitConverter.GetBytes(diff);
                Console.WriteLine("The difference of 2 and 1 is:" + diff + ". Start send data.");

                _serialPort.Send(new byte[] { (byte)CommandType.Reduce, dffBytes[0], dffBytes[1] });
                Console.WriteLine("Finish send result of difference.");
            }
        }

        public void Start()
        {
            _serialPort.Open();
        }
    }
}
